// @ts-ignore
import './index.css'

import {Component} from "react";
import {Layout, Menu} from "antd";
import {withRouter} from "react-router-dom";

import {getRealPathname, getMenuItems, MenuItem} from "../../../utils/menu.util.tsx";

const {Sider} = Layout;

import {name} from '../../../assets/settings.json'

class CustomSider extends Component<any, {
    collapsed: boolean;
    menuItems: MenuItem[];
    openKeys: string[];
}> {
    state = {
        collapsed: false,
        menuItems: [],
        openKeys: []
    }

    /**
     * Description: 处理点击父菜单的回调逻辑
     *
     * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-03-07 17:08:45
     */
    onOpenChange(openKeys: string[]) {
        if (openKeys.length > 0) {
            this.setState({openKeys: [openKeys[openKeys.length - 1]]})
        } else {
            this.setState({openKeys: []})
        }
    }

    /**
     * Description: 初始化菜单栏.
     *
     * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-03-07 17:46:06
     */
    componentDidMount() {
        const menuItems: MenuItem[] = getMenuItems();

        // ~ 初始化菜单
        this.setState({menuItems: menuItems})

        const realPathname = getRealPathname(this.props.location.pathname);
        // ~ (根据 url) 初始化 openKeys
        for (let parent of menuItems) {
            if (parent && "children" in parent && parent.children !== undefined) {
                for (let the of parent.children) {
                    if (the && the.key === realPathname) {
                        this.setState({openKeys: ["key" in parent ? String(parent.key) : '']})
                    }
                }
            }
        }
    }

    render() {
        const {collapsed, menuItems} = this.state;
        const selectedKeys: string[] = [getRealPathname(this.props.location.pathname)]

        return (
            <>
                <Sider collapsible collapsed={collapsed} onCollapse={to => this.setState({collapsed: to})}>
                    <div className="logo">{name}</div>
                    <Menu theme="dark" openKeys={this.state.openKeys} onOpenChange={(openKeys) => this.onOpenChange(openKeys)} selectedKeys={selectedKeys} mode="inline" items={menuItems}/>
                </Sider>
            </>
        )
    }
}

export default withRouter(CustomSider);
